<template>
  <v-container style="display:flex;height:calc(100vh - 64px);flex-direction:column" fluid>
    <practice-frame ref="practiceFrame" practice-model="choose" :setPracticeCallback="setPracticeCallback"
      :clearPracticeConfigCallback="getPracticeConfit" :tryPlayWordSymbolVoice="playAudio">
      <template v-slot:center>
        <div>
          <div v-if="config.titleSwitch" style="font-size: 30px;"> {{ currentWord.word }} </div>
          <p v-if="config.titleExplainSwitch" style="font-size: 20px;">
            {{ config.titleLocalSwitch ? currentWord.meanLocal : currentWord.meanSelf }}
          </p>
          <!-- <div v-if="currentWord.pronunciation != null && currentWord.pronunciation.length > 0&&config.wordSymbol">
            <span @click="playAudio(pronunciation)" v-for="(pronunciation, index) in currentWord.pronunciation"
              v-bind:key="index">
              <small style="font-size: 16px;">{{ pronunciation.region }}[{{ pronunciation.symbol }}]</small>
              <v-icon size="small" icon="mdi-volume-high"/> &nbsp;
            </span>
          </div> -->
          <PronunciationComponent direction="horizon" ref="pronunciationComponent"/>
          <v-btn @click="respond(item,index,'resp_btn_'+index)" :ref="pushBtnToList" class="item-btn" v-bind:key="index" 
          v-for="(item,index) in currentWord.choose" block :color="clickedBtnRefName=='resp_btn_'+index?this.clickedBtnColor:'white'"
            rounded="xl" size="x-large" :id="'resp_btn_'+index">
            <span class="item-btn-content">
              <span v-if="!config.wordChooseSwitch">
                <span v-if="this.config.chooseItemSwitch&&item.meanSelfType">
                  [{{ item.meanSelfType }}].
                </span>
                <span v-else-if="!this.config.chooseItemSwitch&&item.meanLocalType">
                  [{{ item.meanLocalType }}].
                </span>
              </span>
              <span v-if="!config.wordChooseSwitch">{{ this.config.chooseItemSwitch ? item.meanSelf : item.meanLocal }}</span>
              <span v-if="config.wordChooseSwitch">{{ item.word }}</span>
            </span>
            <v-icon color="primary" @click.stop="showChooseItemDetail(item.wordId,originData.assist[index])" style="position: absolute;right:5px;" icon="mdi-information"/>
          </v-btn>
          <p v-if="hint" style="margin-top: 20px">{{ currentWord.remember }}</p>
          <v-btn v-if="!hint&&currentWord.remember!=null" style="margin-top: 20px" @click="hint=true;" 
          class="ma-2" color="indigo" icon="mdi-flash" />
        </div>
      </template>
    </practice-frame>
  </v-container>
  <v-overlay :model-value="overlay" class="align-center justify-center">
    <v-progress-circular color="primary" indeterminate size="64"></v-progress-circular>
  </v-overlay>
</template>

<script>
import PracticeFrame from '@/components/PracticeFrame.vue'
import { nextRow, choose,queryUserPracticeConfig } from "@/api/practice.js";
import PronunciationComponent from '@/components/PronunciationComponent.vue';
export default {
  components: { PracticeFrame,PronunciationComponent },
  name: 'ChooseView',
  data() {
    return {
      originData:[],
      currentWord: { word: '', meanSelf: '', explain: '', wordId: 0 },
      practice: undefined,
      showTitleSwitch: true,
      chooseMode: 2,
      overlay: false,
      config: {},
      retry:false,
      hint:false,
      clickedBtnRefName:'',
      clickedBtnColor:'white',
      replyBtnNode:[]
    }
  },
  created() {
    this.loadingChoose()
    this.getPracticeConfit()
  },
  unmounted(){
    if(this.audio!=null){
      this.audio.pause()
      this.audio = null
    }
  },
  methods: {
    loadingChoose() {
      this.overlay = true
      choose({ bookId: this.$route.params.bookId, practiceModel: 'choose' }).then(() => {
        // this.nextRaw({ bookId: this.$route.params.bookId, practiceModel: 'choose' })
        this.$refs.practiceFrame.nextRaw()
      }).finally(() => this.overlay = false)
    },
    nextRaw() {
      this.overlay = true
      nextRow({ bookId: this.$route.params.bookId, practiceModel: 'choose' }).then(resp => {
        if (resp.data == null) return
        this.$refs.practiceFrame.setPractice(resp.data)
        try {
          this.trans(resp.data);
        } catch (error) {
          console.log(error);
          alert('报错：'+error) 
        }
      }).finally(() => this.overlay = false)
    },
    trans(data) {
      this.replyBtnNode=[]
      if (data == null || data.word == null) {
        return
      }
      this.currentWord.word = data.word.word
      this.currentWord.remember = data.word.remember
      this.currentWord.wordId = data.word.wordId
      this.currentWord.pronunciation=data.word.pronunciation
      this.currentWord.choose = []
      this.originData=data
      for (let i = 0; i < data.assist.length; i++) {
        let assistItem = data.assist[i]
        let chooseItem = {}
        chooseItem.wordId = assistItem.wordId
        chooseItem.word = assistItem.word
        let meanSelf = '', meanSelfTypeObj = '', meanLocalObj = '', meanSelfType = '', meanLocalType = '', meanLocal, index
        if (assistItem.originalMeanings != null) index = this.getRandomInt(0, assistItem.originalMeanings.length == 1 ? 0 : assistItem.originalMeanings.length - 1)
        if(assistItem.originalMeanings!=null)meanSelfTypeObj = assistItem.originalMeanings[index]
        if(meanSelfTypeObj!=null&&meanSelfTypeObj.meaning!=null)
          index = this.getRandomInt(0, meanSelfTypeObj.meaning.length == 1 ? 0 : meanSelfTypeObj.meaning.length - 1)
        if(meanSelfTypeObj!='')meanSelf = meanSelfTypeObj.meaning[index].explain
        meanSelfType = meanSelfTypeObj.type
        if (assistItem.translatedMeanings != null){
          index = this.getRandomInt(0, assistItem.translatedMeanings.length == 1 ? 0 : assistItem.translatedMeanings.length - 1)
          meanLocalObj = assistItem.translatedMeanings[index]
          meanLocalType = meanLocalObj.type
          meanLocal = meanLocalObj.meaning
        }
        chooseItem.meanSelf = meanSelf
        chooseItem.meanSelfType = meanSelfType
        chooseItem.meanLocal = meanLocal
        chooseItem.meanLocalType = meanLocalType
        this.chooseShow(chooseItem)
        if (this.currentWord.wordId == assistItem.wordId) {
          this.currentWord.meanSelf = meanSelf
          chooseItem.right = true
          this.currentWord.meanLocal = meanLocal
          this.currentWord.meanLocalType = meanLocalType
        }
        this.currentWord.choose.push(chooseItem)
      }
      this.retry=false
      this.hint=false
      this.clickedBtnColor='white'
      this.clickedBtnRefName=''
      if(this.config.wordSymbol)
        this.$refs.pronunciationComponent.setResource(this.currentWord.pronunciation)
    },
    chooseShow(chooseItem) {
      if (this.chooseMode == 1) {
        chooseItem.show = chooseItem.meanLocalType + '.' + chooseItem.meanLocal
        return
      }
      if (this.chooseMode == 2) {
        chooseItem.show = chooseItem.meanLocalType + '.' + chooseItem.meanSelf
        return
      }
    },
    setPracticeCallback(practice) {
      try{
        this.trans(practice);
      }catch(error){
        console.error('trans：', error)
      }
      if(this.audio!=null){
        this.audio.pause()
        this.audio=null
      }
    },
    getPracticeConfit(){
      queryUserPracticeConfig({bookId: this.$route.params.bookId, practiceModel: 'choose'}).then(resp=>{
        if(resp.data!=null)this.setPracticeConfit(resp.data.configJsonText);
        else this.setPracticeConfit('')
      })
    },
    setPracticeConfit(choosePracticeStorege) {
      //let choosePracticeStorege = localStorage.getItem('practiceConfig-choose')      
      let parseResult = true
      if (choosePracticeStorege != null) {
        try {
          this.config = JSON.parse(choosePracticeStorege)
        } catch (error) {
          console.error('加载配置失败：', error)
          parseResult = false
        }
      }
      if (!parseResult || choosePracticeStorege == null) {
        this.config = {
          showTitleSwitch: true,
          showChooseItemSwitch: true,
          showTitleExplainSwitch: true,
          titleLocalSwitch: false,
          titleSwitch: true,
          showTitleLocalSwitch: true,
          showAutoPlay:true,
          //name: 'practiceConfig-choose',
          showWordChooseSwitch:true,
          showQuickKeySwitch:true,
          quickKeySwitch:true,
          showAutoPlayResponded:true,
          autoPlayResponded:false,
          showWordSymbolSwitch:true,
          wordSymbol:false,
          showVibrateSwitch:true,
          isVibrate:false
        }
      }
      setTimeout(() => {
        this.$refs.practiceFrame.setPracticeConfig(this.config)
      }, 500);
    },
    showChooseItemDetail(wordId,wordData){
      this.$refs.practiceFrame.getWordDetail(wordId,wordData)
    },
    getRandomInt(min, max) {
      min = Math.ceil(min);
      max = Math.floor(max);
      return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值，含最小值  
    },
    respond(item,index,refName) {
      // console.log(item);
      if(this.config.isVibrate&&"vibrate" in navigator)navigator.vibrate(30);
      this.clickedBtnRefName=refName
      if(!item.right){
        this.retry=true
        this.clickedBtnColor='red'
      }else this.clickedBtnColor='green'
      item.retry=this.retry
      // this.$refs['inputField'].focus();
      // this.$refs.inputField.focus();
      // this.replyBtnNode[index].blur()//vue v-for获取dom
      document.getElementById(refName).blur()
      this.$refs.practiceFrame.reply(item)
    },
    playAudio(pronunciation) {
      if (this.audio != null && pronunciation.resource == this.audioUrl) {
        this.audio.pause()
        this.audio = null
        return
      } else if (pronunciation.resource != this.audioUrl) {
        if (this.audio != null) this.audio.pause()
        this.audio = new Audio(pronunciation.resource)
        this.audio.loop = true
        this.audio.play()
        this.audioUrl = pronunciation.resource
        return
      }
      this.audio = new Audio(pronunciation.resource)
      this.audio.loop = true
      this.audio.play()
      this.audioUrl = pronunciation.resource
    },
    pushBtnToList(el){
      this.replyBtnNode.push(el)
    }
  },
  watch:{
    'config.wordSymbol'(newValue){
      if(newValue&&this.$refs.pronunciationComponent!=null)
        this.$refs.pronunciationComponent.setResource(this.currentWord.pronunciation)
      else
        this.$refs.pronunciationComponent.setResource(null)
    }
  }
}
</script>

<style scoped>
.centerDiv {
  width: 100%;
  text-align: center;
  margin: auto;
}

.div_blur {
  filter: blur(5px);
}

.item-btn {
  text-transform: none;
  height: fit-content;
  margin: 10px auto;
  padding: 10px;
}

.item-btn-content {
  -webkit-line-clamp: 3;
  line-clamp: 3;
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  text-overflow: ellipsis;
  white-space: normal;
}
</style>